pub mod meta;

use std::fs::File;
use serde_json::{from_reader, Value};
use std::io;
use crate::meta::{ResourceDescriptor, Resource};
use std::collections::HashMap;
use std::io::Read;

#[derive(Default)]
pub struct Resources {
    text_resources: HashMap<String, String>
}

impl Resources {
    const MANIFEST_NAME: &'static str = "manifest.json";
    pub fn open(path: &str) -> io::Result<Self> {
        let mut this = Resources::default();

        let manifest = File::open(format!("{}/{}", path, Self::MANIFEST_NAME))?;

        let manifest: meta::Manifest = from_reader(manifest)?;

        for res_name in manifest.resources {
            let res: ResourceDescriptor = from_reader(File::open(format!("{}/{}.json", path, res_name))?)?;
            match &res.resource {
                Resource::Image { .. } => {}
                Resource::Text => {
                    let mut context = File::open(format!("{}/{}", path, res.path))?;
                    let mut cx = String::new();
                    context.read_to_string(&mut cx);

                    this.text_resources.insert(res_name, cx);
                }
                Resource::Bin => {}
            }
        }

        Ok(this)
    }

    pub fn get_text(&self, name: &str) -> Option<String> {
        self.text_resources.get(name).map(|string| String::from(string))
    }
}